<!-- RestaurantTree.vue -->
<template>
  <div class="enhanced-tree-container">
    <div
        v-for="restaurant in restaurants"
        :key="restaurant.id"
        class="restaurant-node"
    >
      <div class="node-header" @click="toggleNode(restaurant)">
        <i class="expand-icon" :class="`fas fa-chevron-${restaurant.expanded ? 'down' : 'right'}`"></i>
        <div class="node-info">
          <span class="node-icon fas fa-store"></span>
          <h3 class="node-title">{{ restaurant.name }}</h3>
        </div>
        <div class="node-actions">
          <button class="action-btn success" @click.stop="showDepartmentDialog('add', restaurant)">
            <i class="fas fa-plus"></i>
          </button>
          <button class="action-btn warning" @click.stop="showRestaurantDialog('edit', restaurant)">
            <i class="fas fa-edit"></i>
          </button>
          <button class="action-btn danger" @click.stop="deleteRestaurants(restaurant)">
            <i class="fas fa-trash"></i>
          </button>
        </div>
      </div>

      <transition name="slide-fade">
        <div v-show="restaurant.expanded" class="children-container">
          <div
              v-for="department in restaurant.departments"
              :key="department.id"
              class="department-node"
          >
            <div class="node-header" @click="toggleDepartment(department)">
              <i class="expand-icon" :class="`fas fa-chevron-${department.expanded ? 'down' : 'right'}`"></i>
              <div class="node-info">
                <span class="node-icon fas fa-boxes"></span>
                <h4 class="node-title">{{ department.name }}</h4>
              </div>
              <div class="node-actions">
                <button class="action-btn success"  @click.stop="showDishDialog('add', department)">
                  <i class="fas fa-plus"></i>
                </button>
                <button class="action-btn warning" @click.stop="showDepartmentDialog('edit', department)">
                  <i class="fas fa-edit"></i>
                </button>
                <button class="action-btn danger" @click.stop="deleteDepartments(department)">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </div>

            <transition name="slide-fade">
              <div v-show="department.expanded" class="children-container">
                <div
                    v-for="dish in department.dishes"
                    :key="dish.id"
                    class="dish-node"
                    @click="$emit('node-click', dish)"
                >
                  <div class="node-info">
                    <span class="node-icon fas fa-utensils"></span>
                    <span class="node-title">{{ dish.name }}</span>
                  </div>
                  <div class="node-meta">
                    <span class="price">¥{{ dish.price.toFixed(2) }}</span>
                    <span class="stock">{{ dish.stock }}份</span>
                  </div>
                </div>
              </div>
            </transition>
          </div>
        </div>
      </transition>
    </div>

    <!-- 弹窗组件 -->
    <TreeDialog
        :visible="dialogVisible"
        :type="dialogType"
        :data="currentNode"
        @submit="handleDialogSubmit"
        @close="dialogVisible = false"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {
  createRestaurant,
  updateRestaurant,
  deleteRestaurant,
  addDepartment,
  updateDepartment,
  deleteDepartment,
  addDish,
  updateDish
} from '@/api/index'
import TreeDialog from "@/components/Admin/TreeDialog.vue";

const props = defineProps(['restaurants'])
const emit = defineEmits(['node-click', 'refresh'])

const dialogVisible = ref(false)
const dialogType = ref('add')
const currentNode = ref(null)

// 显示不同弹窗
const showRestaurantDialog = (type, node) => {
  dialogType.value = type
  currentNode.value = node || { name: '', description: '' }
  dialogVisible.value = true
}

const showDepartmentDialog = (type, context) => {
  dialogType.value = type
  currentNode.value = type === 'add'
      ? { restaurantId: context.id, name: '' }
      : { ...context }
  dialogVisible.value = true
}

// 弹窗提交处理
// 修改弹窗提交处理逻辑
const handleDialogSubmit = async (formData) => {
  try {
    let res;
    switch(dialogType.value) {
      case 'add-restaurant':
        res = await createRestaurant(formData);
        break;
      case 'edit-restaurant':
        res = await updateRestaurant(formData.id, formData);
        break;
      case 'add-department':
        res = await addDepartment(formData);
        break;
      case 'edit-department':
        res = await updateDepartment(formData.id, formData);
        break;
    }

    // 使用可选链操作符进行安全访问
    if (res?.success) {
      console.log(`${dialogType.value}成功`, res.data);
      emit('refresh');
    } else {
      console.error('操作失败:', res?.message || '未知错误');
    }
  } catch (error) {
    console.error('请求异常:', error.response?.data || error.message);
  }
}

// 删除操作
const deleteRestaurants = async (restaurant) => {
  if (confirm(`确定删除餐厅【${restaurant.name}】及其所有下属内容？`)) {
    await deleteRestaurant(restaurant.id)
    emit('refresh')
  }
}

const deleteDepartments = async (department) => {
  if (confirm(`确定删除部门【${department.name}】及其所有菜品？`)) {
    await deleteDepartment(department.id)
    emit('refresh')
  }
}

// 节点展开控制
const toggleNode = (node) => {
  node.expanded = !node.expanded
  if (node.expanded && !node.departments?.length) {
    // 可在此处添加部门加载逻辑
  }
}
</script>

<style scoped>
.enhanced-tree-container {
  width: 480px;
  min-width: 400px;
  padding: 1rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.node-header {
  display: flex;
  align-items: center;
  padding: 12px;
  margin: 4px 0;
  background: #f8fafc;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  &:hover {
    background: #f1f5f9;
    transform: translateX(4px);
  }
}

.expand-icon {
  width: 24px;
  color: #64748b;
  transition: transform 0.2s;
}

.node-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  .node-icon {
    color: #3b82f6;
    width: 20px;
  }
  .node-title {
    margin: 0;
    font-weight: 500;
    color: #1e293b;
  }
}

.node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
  .node-header:hover & {
    opacity: 1;
  }
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  &.success {
    background: #10b98120;
    color: #10b981;
    &:hover { background: #10b98130; }
  }
  &.warning {
    background: #f59e0b20;
    color: #f59e0b;
    &:hover { background: #f59e0b30; }
  }
  &.danger {
    background: #ef444420;
    color: #ef4444;
    &:hover { background: #ef444430; }
  }
}

.children-container {
  margin-left: 32px;
  padding-left: 12px;
  border-left: 2px dashed #e2e8f0;
}

.dish-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin: 4px 0;
  background: #fff;
  border-radius: 4px;
  transition: all 0.2s;
  &:hover {
    background: #f8fafc;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  }
  .node-meta {
    font-size: 0.9em;
    color: #64748b;
    .price {
      color: #10b981;
      margin-right: 12px;
    }
  }
}

/* 过渡动画 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}
.slide-fade-leave-active {
  transition: all 0.2s ease-in;
}
.slide-fade-enter-from,
.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>